﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;

namespace ReportGenerators.BanHang
{
    public partial class FrmThongKeBanHang : BasicForms.FrmClose
    {
        public FrmThongKeBanHang()
        {
            InitializeComponent();
        }

        private void FrmThongKeBanHang_Load(object sender, EventArgs e)
        {
            GuiUtilities.FrmProgressBar.StartShowProgress();
            //this.vatTuHangHoaTableAdapter.Fill(this.dsThongKeBanHang.VatTuHangHoa);
            //this.doiTuongNghiepVuTableAdapter.Fill(this.dsThongKeBanHang.DoiTuongNghiepVu);

            cmbKyBaoCao.SelectedIndex = 0;

            cmbKho.DataSource = DanhMucKho.Instance.DataView;
            cmbKho.DisplayColumn = "Ten";
            cmbKho.ValueColumn = "ID";
            cmbKho.AddVisibleColumn("Ma", "Mã");
            cmbKho.AddVisibleColumn("Ten", "Tên");
            cmbKho.EditValue = Guid.Empty;

            cmbNhomVatTuHangHoa.DataSource = DanhMucNhomVatTuHangHoa.Instance.DataView;
            cmbNhomVatTuHangHoa.DisplayColumn = "Ten";
            cmbNhomVatTuHangHoa.ValueColumn = "ID";
            cmbNhomVatTuHangHoa.AddVisibleColumn("Ma", "Mã");
            cmbNhomVatTuHangHoa.AddVisibleColumn("Ten", "Tên");

            dsThongKeBanHang.DoiTuongNghiepVu.Merge(DanhMucDoiTuongNghiepVu.GetDanhMucNhaCungCap().DataTable);

            dsThongKeBanHang.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.GetDanhMucHangHoa().DataTable);

            chkChooseAllDoiTac.Checked = true;
            chkChooseAllVatTuHangHoa.Checked = true;

            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewDsDoiTac.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewDsVatTuHangHoa.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }

            GuiUtilities.FrmProgressBar.FinishShowProgress();
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                DateTime ngayBatDau = dtNgayBatDau.DateTime;
                DateTime ngayKetThuc = dtNgayBatDau.DateTime;
                switch (cmbKyBaoCao.Text)
                {
                    case "Hôm nay":
                        dtNgayBatDau.Enabled = true;
                        dtNgayKetThuc.Enabled = true;
                        DateTime now = AccountingLibs.CommonLib.GetSystemDateTime();
                        ngayBatDau = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
                        ngayKetThuc = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
                        break;
                    case "Tùy chọn":
                        dtNgayBatDau.Enabled = true;
                        dtNgayKetThuc.Enabled = true;
                        ngayBatDau = new DateTime(AccountingLibs.Config.NamTaiChinh, 1, 1);
                        ngayKetThuc = DateTime.Now;
                        break;
                    case "Cả năm":
                        dtNgayBatDau.Enabled = false;
                        dtNgayKetThuc.Enabled = false;
                        ngayBatDau = new DateTime(AccountingLibs.Config.NamTaiChinh, 1, 1);
                        ngayKetThuc = new DateTime(AccountingLibs.Config.NamTaiChinh, 12, 31, 23, 59, 59);
                        break;
                    case "Quý I":
                        dtNgayBatDau.Enabled = false;
                        dtNgayKetThuc.Enabled = false;
                        ngayBatDau = new DateTime(AccountingLibs.Config.NamTaiChinh, 1, 1);
                        ngayKetThuc = new DateTime(AccountingLibs.Config.NamTaiChinh, 3, 31, 23, 59, 59);
                        break;
                    case "Quý II":
                        dtNgayBatDau.Enabled = false;
                        dtNgayKetThuc.Enabled = false;
                        ngayBatDau = new DateTime(AccountingLibs.Config.NamTaiChinh, 4, 1);
                        ngayKetThuc = new DateTime(AccountingLibs.Config.NamTaiChinh, 6, 30, 23, 59, 59);
                        break;
                    case "Quý III":
                        dtNgayBatDau.Enabled = false;
                        dtNgayKetThuc.Enabled = false;
                        ngayBatDau = new DateTime(AccountingLibs.Config.NamTaiChinh, 7, 1);
                        ngayKetThuc = new DateTime(AccountingLibs.Config.NamTaiChinh, 9, 30, 23, 59, 59);
                        break;
                    case "Quý IV":
                        dtNgayBatDau.Enabled = false;
                        dtNgayKetThuc.Enabled = false;
                        ngayBatDau = new DateTime(AccountingLibs.Config.NamTaiChinh, 10, 1);
                        ngayKetThuc = new DateTime(AccountingLibs.Config.NamTaiChinh, 12, 31, 23, 59, 59);
                        break;
                    default:
                        try
                        {
                            dtNgayBatDau.Enabled = false;
                            dtNgayKetThuc.Enabled = false;
                            string strThang = ((string)cmbKyBaoCao.SelectedItem).Substring(((string)(cmbKyBaoCao.SelectedItem)).LastIndexOf(" "));
                            int thang = int.Parse(strThang);

                            ngayBatDau = new DateTime(AccountingLibs.Config.NamTaiChinh, thang, 1);
                            ngayKetThuc = new DateTime(AccountingLibs.Config.NamTaiChinh, thang,
                                            DateTime.DaysInMonth(AccountingLibs.Config.NamTaiChinh, thang), 23, 59, 59);
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Trace.WriteLine(ex.ToString());
                        }
                        break;
                }
                dtNgayBatDau.DateTime = ngayBatDau;
                dtNgayKetThuc.DateTime = ngayKetThuc;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void chkChooseAllVatTuHangHoa_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataRow row in dsThongKeBanHang.VatTuHangHoa.Rows)
            {
                row["Choose"] = chkChooseAllVatTuHangHoa.Checked;
            }
        }

        private void chkChooseAllDoiTac_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataRow row in dsThongKeBanHang.DoiTuongNghiepVu.Rows)
            {
                row["Choose"] = chkChooseAllDoiTac.Checked;
            }
        }

        private void cmbNhomVatTuHangHoa_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbNhomVatTuHangHoa.EditValue = Guid.Empty;
        }
        private void cmbNhomVatTuHangHoa_EditValueChanged(object sender, EventArgs e)
        {
            if (cmbNhomVatTuHangHoa.EditValue is Guid && (Guid)cmbNhomVatTuHangHoa.EditValue != Guid.Empty)
            {
                dsThongKeBanHang.VatTuHangHoa.Clear();
                string filter = string.Format("NhomVatTuHangHoaID = '{0}'", cmbNhomVatTuHangHoa.EditValue);
                dsThongKeBanHang.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.Filter(filter).DataView.ToTable());
            }
            else
            {
                dsThongKeBanHang.VatTuHangHoa.Clear();
                dsThongKeBanHang.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.GetDanhMucHangHoa().DataView.ToTable());
            }
            chkChooseAllVatTuHangHoa.Checked = false;
            chkChooseAllVatTuHangHoa.Checked = true;
        }

        private void cmbKho_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbKho.EditValue = Guid.Empty;
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            GuiUtilities.FrmProgressBar.StartShowProgress();

            DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            string kyBaoCao = cmbKyBaoCao.Text;
            if (kyBaoCao == "Cả năm") kyBaoCao = "Năm " + AccountingLibs.Config.NamTaiChinh.ToString();
            else if (kyBaoCao == "Tùy chọn") kyBaoCao = string.Format("Từ ngày {0}/{1}/{2} đến ngày {3}/{4}/{5}",
                                       ngayBatDau.Day, ngayBatDau.Month, ngayBatDau.Year,
                                       ngayKetThuc.Day, ngayKetThuc.Month, ngayKetThuc.Year);

            SqlConnection con = new SqlConnection(AccountingLibs.LocalSettings.ConnectString);
            try
            {
                SqlCommand cmd = con.CreateCommand();

                string nhaCungCapCondition = "B.DoiTuongNghiepVu1ID IN (";
                foreach (DataRow row in dsThongKeBanHang.DoiTuongNghiepVu.Rows)
                {
                    if ((bool)row["Choose"])
                    {
                        nhaCungCapCondition += string.Format("'{0}', ", row["ID"]);
                    }
                }
                if (nhaCungCapCondition.EndsWith("', ")) nhaCungCapCondition = nhaCungCapCondition.Substring(0, nhaCungCapCondition.Length - 2) + ")";
                else nhaCungCapCondition = "1 = 0";

                string vatTuHangHoaCondition = "VatTuHangHoa1ID IN (";
                foreach (DataRow row in dsThongKeBanHang.VatTuHangHoa.Rows)
                {
                    if ((bool)row["Choose"])
                    {
                        vatTuHangHoaCondition += string.Format("'{0}', ", row["ID"]);
                    }
                }
                if (vatTuHangHoaCondition.EndsWith("', ")) vatTuHangHoaCondition = vatTuHangHoaCondition.Substring(0, vatTuHangHoaCondition.Length - 2) + ")";
                else vatTuHangHoaCondition = "1 = 0";

                string khoCondition = "1 = 1";
                if ((Guid)cmbKho.EditValue != Guid.Empty) khoCondition = string.Format("B.Kho1ID = '{0}'", cmbKho.EditValue);
                cmd.CommandText = string.Format("SELECT A.So, A.Ngay, DTNV.Ten TenDoiTac, Kho.Ten TenKho, D.Ten TenHangHoa, E.Ten TenNhomHangHoa, D.DonViTinh, \n" +
                                                "           C.Value1 SoLuong, C.Value12 GiaBia, C.Value8 ChietKhau, C.Value5 ThanhTien \n" +
                                                "FROM LoaiChungTu LCT INNER JOIN ChungTu A ON LCT.ID = A.LoaiChungTuID \n" +
                                                "       INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuGocID \n" +
                                                "       INNER JOIN DoiTuongNghiepVu DTNV ON B.DoiTuongNghiepVu1ID = DTNV.ID \n" +
                                                "       INNER JOIN Kho ON B.Kho1ID = Kho.ID \n" +
                                                "       INNER JOIN  KhoanMucChungTu C ON B.ChungTuID = C.ChungTuID \n" +
                                                "       INNER JOIN VatTuHangHoa D ON C.VatTuHangHoa1ID = D.ID \n" +
                                                "       INNER JOIN NhomVatTuHangHoa E ON D.NhomVatTuHangHoaID = E.ID \n" +
                                                "WHERE LCT.Ma = 'HoaDonBanHang' OR LCT.Ma = 'HoaDonBanLe' \n" +
                                                "       AND @ThoiDiemDau <= A.Ngay AND A.Ngay <= @ThoiDiemCuoi  \n" +
                                                "       AND {0} AND {1} AND {2}  \n" +
                                                "ORDER BY B.Ngay",
                                                nhaCungCapCondition, vatTuHangHoaCondition, khoCondition);


                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@ThoiDiemDau", ngayBatDau);
                cmd.Parameters.AddWithValue("@ThoiDiemCuoi", ngayKetThuc);

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                dsThongKeBanHang.Detail_ThongKeBanHang.Clear();
                da.Fill(dsThongKeBanHang.Detail_ThongKeBanHang);

                //gridControlThongKeBanLe.DataSource = ds.Select_Detail_KhoanMucThongKeBanLe;
                FormatNumberInGridView(gridView);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.ToString());
            }
            finally
            {
                con.Close();
                con = null;
            }
            GuiUtilities.FrmProgressBar.FinishShowProgress();
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            gridControl.ShowPrintPreview();
        }
    }
}
